﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;

using LowLevelGraphics.ColorSpaces;

namespace LowLevelGraphics.Filter
{
    /// <summary>
    /// Eliminates all colored regions
    /// </summary>
    public class EliminateColoredRegions : BaseForeBackgroundColorFilter
    {
        protected float m_fThreshold = 0.0f;

        /// <summary>
        /// default constructor
        /// </summary>
        public EliminateColoredRegions()
        {
        }

        /// <summary>
        /// primary constructor, specify threshold directly
        /// </summary>
        /// <param name="_fThreshold"></param>
        public EliminateColoredRegions(float _fThreshold)
        {
            m_fThreshold = _fThreshold;
        }

        /// <summary>
        /// used by clone to create a deep copy
        /// </summary>
        /// <param name="_eliminateColoredRegions"></param>
        internal EliminateColoredRegions(EliminateColoredRegions _eliminateColoredRegions)
        {
            this.m_fThreshold = _eliminateColoredRegions.m_fThreshold;
        }

        /// <summary>
        /// Gets or sets threshold
        /// </summary>
        public float Threshold
        {
            get { return m_fThreshold; }
            set { m_fThreshold = value; }
        }

        /// <summary>
        /// executes this filter
        /// </summary>
        /// <param name="_bitmap"></param>
        /// <returns></returns>
        public override UnsafeBitmap Execute(UnsafeBitmap _bitmap)
        {
            UnsafeBitmap bitmap = _bitmap;

            int nHeight = bitmap.Height;
            int nWidth = bitmap.Width;

            Color color = Color.Transparent;

            int y = 0;
            int x = 0;
            double cr = 0;

            for (y = 0; y < nHeight; y++)
            {
                for (x = 0; x < nWidth; x++)
                {
                    color = bitmap.GetPixel(x, y);
                    YCbCr ycbcr = new YCbCr(color);
                     cr = 0;
                    if (ycbcr.Cr < m_fThreshold)
                    {
                        cr = 0;
                    }
                    else
                    {
                        cr = ycbcr.Cr;
                    }
                    if (!(cr > 0))
                    {
                        bitmap.SetPixel(x, y, m_ColorBackground);
                    }
                }
            }
            return _bitmap;
        }

        /// <summary>
        /// use this to create a deep copy
        /// </summary>
        /// <returns></returns>
        public override object Clone()
        {
            return new EliminateColoredRegions(this);
        }
    }
}
